package util.ThreadPoolTaskConfig;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolTaskConfig {

    /*
        默认情况下，在创建了线程池后，线程池中的线程数为0，当有任务来之后，就会创建一个线程去执行任务，
         当线程池中的线程数目达到corePoolSize后，就会把到达的任务放到缓存队列当中；
       当队列满了，就继续创建线程，当线程数量大于等于maxPoolSize后，开始使用拒绝策略拒绝
     */

    /**
     * 核心线程数（默认线程数）
     */
    private static final int corePoolSize = 3;
    /**
     * 最大线程数
     */
    private static final int maxPoolSize = 20;
    /**
     * 允许线程空闲时间（单位：默认为秒）
     */
    private static final int keepAliveTime = 20;
    /**
     * 缓冲队列大小
     */
    private static final BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1000);
    /**
     * 线程池名前缀
     */
    private static final String threadNamePrefix = "golxen-rsms-service-";

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            corePoolSize,
            maxPoolSize,
            keepAliveTime, TimeUnit.SECONDS,
            workQueue
    );
    public static ThreadPoolExecutor taskExecutor() {
//        executor = new ThreadPoolExecutor(
//                corePoolSize,
//                maxPoolSize,
//                keepAliveTime, TimeUnit.SECONDS,
//                workQueue
//                );
//        executor.setCorePoolSize(corePoolSize);
//        executor.setMaximumPoolSize(maxPoolSize);
//        executor.setWorkQueue(queueCapacity);
//        executor.setKeepAliveTime(keepAliveTime, TimeUnit.SECONDS);
//        executor.setThreadNamePrefix(threadNamePrefix);

        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy：由调用线程（提交任务的线程）处理该任务
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //抛异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        // 初始化
//        executor.initialize();
        return executor;
    }
}
